﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using TomNet.Data;
using TomNet.Entity;

namespace TomNet.AspNetCore.Mvc.Filters
{
    public class ModelValidateFilter : IAsyncActionFilter
    {
        private readonly ILogger _logger;
        private readonly ILoggerFactory _loggerFactory;

        public ModelValidateFilter(ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;
            _logger = _loggerFactory.CreateLogger(GetType());
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context.ModelState.IsValid)
            {
                await next();
            }
            else
            {
                //　输出日志
                _logger.LogError("参数验证失败");
                var result = new OpResult<string>();
                result.NotOK(status: ApiResultCode.InvalidParamater, msg: "参数验证失败");
                // 标准的Http状态码处理方式
                // context.Result = ApiResult.ToApiResult(result);
                // 这是传统的处理方式，并不将异常信息以HTTP状态码返回给客户端
                context.Result = new OkObjectResult(result);
            }
        }
    }
}
